package cn.itcast.mq.listeners;

import cn.itcast.mq.config.RabbitmqConfig;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class SpringRabbitListener {
    // 利用RabbitListener来声明要监听的队列信息
    // 将来一旦监听的队列中有了消息，就会推送给当前服务，调用当前方法，处理消息。
    // 可以看到方法体中接收的就是消息体的内容
    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage(String msg) throws InterruptedException {
        System.out.println("spring 消费者接收到消息：【" + msg + "】");
    }

    @RabbitListener(queues = "fanout.queue1")
    public void listenFanoutQueue1Message(String msg) throws InterruptedException {
        System.out.println("FanoutQueue1 消费者接收到消息：【" + msg + "】");
    }

    @RabbitListener(queues = "fanout.queue2")
    public void listenFanoutQueue2Message(String msg) throws InterruptedException {
        System.err.println("FanoutQueue2 消费者接收到消息：【" + msg + "】");
    }

    @RabbitListener(queues = "object.queue")
    public void listenObjectQueueMessage(Map<String, Object> msg) throws InterruptedException {
        System.out.println("spring 消费者接收到消息：【" + msg + "】");
    }


    /*监听只针对 Queues 也就是队列*/
    //监听email队列
    @RabbitListener(queues = {RabbitmqConfig.QUEUE_INFORM_EMAIL})
    public void receive_email(Object msg, Message message, Channel channel) {
        System.out.println("QUEUE_INFORM_EMAIL msg" + msg);
        //System.out.println(message);
        //System.out.println(channel);
    }

    //监听sms队列
    @RabbitListener(queues = {RabbitmqConfig.QUEUE_INFORM_SMS})
    public void receive_sms(Object msg, Message message, Channel channel) {
        System.out.println("QUEUE_INFORM_SMS msg" + msg);
        //System.out.println(message);
        //System.out.println(channel);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitmqConfig.QUEUE_NAME_1),
            exchange = @Exchange(name = "amq.direct", type = ExchangeTypes.DIRECT),
            key = RabbitmqConfig.ROUTING_KEY_1
    ))
    public void receiveQ1(String message) {
        System.out.println("RoutingReceiver1 received message: " + message);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitmqConfig.QUEUE_NAME_2),
            exchange = @Exchange(name = "amq.direct", type = ExchangeTypes.DIRECT),
            key = {RabbitmqConfig.ROUTING_KEY_2, RabbitmqConfig.ROUTING_KEY_1}
    ))
    public void receiveQ2(String message) {
        System.out.println("RoutingReceiver2 received message: " + message);
    }
}